package zhongbo.javaweb.instagram.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import zhongbo.javaweb.instagram.dto.JsonRespDto;
import zhongbo.javaweb.instagram.enums.RespErrorCode;
import zhongbo.javaweb.instagram.util.SpringWebUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 说明：异常统一管理
 * <p>
 * #@ControllerAdvice
 * 增强Controller注解, 使用场景:
 * 1.全局异常处理
 * 2.全局数据绑定
 * 3.全局数据预处理
 * <p>
 *
 * @author 钟波notebook
 * @see <a href="https://www.cnblogs.com/gdwkong/articles/8660002.html">8660002.html</a>
 * @since 2020年01月20日 星期一 18:27:55
 */
@ControllerAdvice
@Slf4j
public class AllExceptionHandler {
    /**
     * 判断错误是否是已定义的已知错误，不是则由未知错误代替，同时记录在log中
     *
     * @param e Exception
     * @return JsonRespDto
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonRespDto<Object> exceptionGet(Exception e) {
        HttpServletRequest request = SpringWebUtil.getContextRequest();
        String requestInfo = SpringWebUtil.getRequestInfo(request);
        HttpHeaders requestHeaders = SpringWebUtil.getRequestHeaders(request);
        if (e != null) {
            log.error("【系统异常】{}; reqHeaders:{} \r\n{}", requestInfo, requestHeaders, e);
            return new JsonRespDto<>().makeError(RespErrorCode.ERROR).setData(readStackTrace(e)).appendMsg(" " + e.getMessage());
        }
        log.error("【系统异常】未知异常 {}", requestInfo);
        return new JsonRespDto<>().makeError(RespErrorCode.ERROR);
    }

    private String readStackTrace(Throwable throwable) {
        StringWriter stringWriter = new StringWriter();
        try (PrintWriter printWriter = new PrintWriter(stringWriter)) {
            throwable.printStackTrace(printWriter);
        }
        return stringWriter.toString();
    }
}
